import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {Image, message, Upload} from 'antd';
import {reqDeleteImg} from "../../apis";
import {BASE_IMG_URL} from "../../utils/constants";
const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
const PictureWall = ({imgs}) => {

    // 是否开启大图预览
    const [previewOpen, setPreviewOpen] = useState(false);
    // 大图src
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState([
        /*{
       uid: '-1', // 每个file都有自己唯一的id
       name: 'xxx.png', // 图片文件名
       status: 'done', // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
       url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', // 图片地址
     },*/
    ]);

    // 接收传递的imgs
    if (imgs && imgs.length>0) {
        let imgList = imgs.map((img, index) => ({
            uid: -index, // 每个file都有自己唯一的id
            name: img, // 图片文件名
            status: 'done', // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
            url: BASE_IMG_URL + img
        }))

        setFileList(imgList)
    }

    // 大图预览
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
    };
    // 上传图片
    const handleChange = async({ file,fileList: newFileList }) => {
        // 一旦上传成功, 将当前上传的file的信息修正(name, url)
        console.log('文件上传信息',file, fileList)
        if(file.status==='done') {
            const result = file.response  // {status: 0, data: {name: 'xxx.jpg', url: '图片地址'}}
            if(result.status===0) {
                message.success('上传图片成功!')
                const {name, url} = result.data
                file = fileList[fileList.length-1]
                file.name = name
                file.url = url
            } else {
                message.error('上传图片失败')
            }
        } else if (file.status==='removed') { // 删除图片
            const result = await reqDeleteImg(file.response.data.name)
            if (result.status===0) {
                message.success('删除图片成功!')
            } else {
                message.error('删除图片失败!')
            }
        }

        setFileList(newFileList)
    };
    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none',
            }}
            type="button"
        >
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </button>
    );
    return (
        <>
            <Upload
                action="/manage/img/upload"
                accept='image/*'  /*只接收图片格式*/
                name='image' /*请求参数名*/
                listType="picture-card"
                fileList={fileList} /*所有已上传图片文件对象的数组*/
                onPreview={handlePreview}
                onChange={handleChange}
            >
                {fileList.length >= 3 ? null : uploadButton}
            </Upload>
            {previewImage && (
                <Image
                    wrapperStyle={{
                        display: 'none',
                    }}
                    preview={{
                        visible: previewOpen,
                        onVisibleChange: (visible) => setPreviewOpen(visible),
                        afterOpenChange: (visible) => !visible && setPreviewImage(''),
                    }}
                    src={previewImage}
                />
            )}
        </>
    );
};
export default PictureWall;